package com.msf.common.base.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.msf.common.constant.BizConstant;
import com.msf.common.domain.dto.LoginModel;
import com.msf.common.domain.query.ExcelQuery;
import com.msf.common.domain.vo.Result;
import com.msf.common.utils.AnnotationUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Description: Controller基类
 */
@Slf4j
public class BaseCommonController<T, S extends IService<T>> {
    @Autowired
    protected S service;

    /**
     * 导出excel
     */
    protected void exportXls(HttpServletResponse response, Class<T> clazz, ExcelQuery excelQuery) throws IOException {
        LoginModel sysUser = (LoginModel) SecurityUtils.getSubject().getPrincipal();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String title = StringUtils.isEmpty(excelQuery.getTitle()) ? BizConstant.EXCEL_EXPORT_DEFAULT_NAME : excelQuery.getTitle();
        String fileName = URLEncoder.encode(title, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        //查询条件关键字keywords解析
        QueryWrapper<T> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(excelQuery.getKeywords())){
            wrapper = AnnotationUtil.processCommonSearchKeywords(wrapper, clazz,excelQuery.getKeywords());
        }
        List<T> list = service.list(wrapper);
        //数据字典转换
        EasyExcel.write(response.getOutputStream(), clazz)
                .autoCloseStream(Boolean.FALSE)
                .sheet(title)
                .doWrite(list);
    }

    /**
     * 通过excel导入数据
     */
    protected Result<?> importExcel(HttpServletRequest request, HttpServletResponse response, Class<T> clazz) {
        return null;
    }
}
